<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  searchEngine
 */

class m_searchEngine_services_indexationService extends f_core_Service
{
    private static $instances;

    private $page;
    private $content;
    private $pageTitle;

    private function  __construct($page)
    {
        $this->page = $page;
    }

    /**
     * @return m_searchEngine_services_indexationService
     */
    public static function getInstance($page)
    {
        if(!isset(self::$instances[$page->getLang()][$page->getUniqueId()]))
        {
            self::$instances[$page->getLang()][$page->getUniqueId()] = new self($page);
        }
        return self::$instances[$page->getLang()][$page->getUniqueId()];
    }

    public function setPageTitle($value)
    {
        $this->pageTitle = $value;
        return $this;
    }

    public function getPageTitle()
    {
        return $this->pageTitle;
    }

    public function getPageContent($indexContext = false)
    {
        if(!isset($this->content) || $indexContext == true)
        {            
            f_core_Context::getInstance()->setContext("currentPage", $this->page);
            f_core_Context::getInstance()->setContext("frontOffice", $this->page);
            f_core_Context::getInstance()->setContext("indexation", $indexContext);

            $tpl = f_template_Template::getInstance()->disableCache();

            $tpl->setModuleTemplate("website", "front/block/BaseBlocks.html");

            if(is_null($this->page->getContent()))
            {
                $pageContent = "";
            }
            else
            {
                $pageContent = $this->getBlocks();
            }
            
            $tpl->assign("content", $pageContent);

            $this->content = $tpl->render();
            $this->setPageTitle(f_core_Context::getInstance()->getContext('frontOffice')->getMetaTitle());
        }
        return $this->content;
    }

    public function getBlocks()
    {
        $blocks = $this->page->getAllBlocks();

        $result = "";
        
        foreach($blocks as $block)
        {
            $file = f_file_Resolver::getModuleFilePath($block["module"], "config/blocks.xml");

            $xmlBlock = f_xml_Xpath::getInstance($file)->fromXpath("block[@action='".$block["action"]."']")->getElement();

            $isIndexable = true;
            
            if($xmlBlock->getAttributeValue("isIndexable") == "false")
            {
                $isIndexable = false;
            }

            if($isIndexable)
            {
                $result .= "{block ".$block['rawValues']."}";
            }
        }

        return $result;
    }

    public function getLinksToCurrentPage()
    {      
        $result = array();

        $content = strip_tags($this->getPageContent(), "<a>");

        $url = $this->page->getCompleteUrl();
        $url = str_replace('/', '\/', $url);

        preg_match_all('`href="'.$url.'\/(.*?)"`', $content, $rawParams);
        $links = array_unique($rawParams[1]);

        if(count($links) > 0)
        {
            foreach($links as $link)
            {
                preg_match('/<(.*?)>/', $this->page->getUrl(true), $matches);

                if(isset($matches[1]))
                {
                    $model = $matches[1];

                    $url = substr($url, 1);
                    if($url !== false)
                    {
                        $suffix['model'] = $model;
                        $suffix['url'] = $link;
                        
                        $doc = f_document_Provider::getInstance()->loadDocuments($suffix['model'])
                                                        ->whereIsEqual('url', $suffix['url'])
                                                        ->whereIsEqual('websiteId', $this->page->getWebsite()->getUniqueId())
                                                        ->retrieveFirstDocument($this->page->getLang());
                    }
                }

                if(isset($doc) && !is_null($doc))
                {
                    $result[] = $doc;
                }
            }
        }
        return $result;
    }

    public function getDocumentIndexParams($url, $document)
    {
		$rootNode = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode("website")->getAllWebsites();
        $root = $rootNode[0]->getUrl();
        $url = str_replace("http://".$root, "", $url);
        echo $url."\n";
        $index = f_document_Provider::getInstance()->createNewDocument('seachEngine/index')->setUrl($url)
                                                                ->setWebsiteId($this->page->getWebsiteId())
                                                                ->setLang($this->page->getLang());

        if(is_object($document) && $document instanceof m_website_documents_Page)
        {
            $content = $this->getPageContent();
        }
        else
        {
            $content = $document->getContent();
        }
        
        $index  ->setContent($this->getCleanContent($content))
                ->setLabel($document->getLabel());

        return $index;
    }

    private function getCleanContent($content)
    {
        $content = strip_tags($content);
        $content = htmlspecialchars_decode($content);
        $content = html_entity_decode($content, ENT_COMPAT, "UTF-8");
        $content = preg_replace('/\s\s+/', ' ', $content);
        $content = preg_replace('/\n+/', ' ', $content);

        return trim($content);
    }
}
